package com.lhl.blog.common.advice;

import com.lhl.blog.common.exception.BlogException;
import com.lhl.blog.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@ResponseBody
//@ResponseBody 由于返回的是数据不是视图，所以要加上这个注解
@ControllerAdvice
@Slf4j
public class ExceptionAdvice {

    //捕获异常（以注解里的为主）
    @ExceptionHandler(Exception.class)
    public Result handel(Exception e){
        log.error("发生异常，e：{}",e);
        return Result.fail("发生错误，"+e.getMessage());
    }

    @ExceptionHandler(BlogException.class)
    public Result blogException(Exception e){
        log.error("发生错误，e：{}",e);
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result handler(NoResourceFoundException e){
        log.error("文件不存在，e：{}",e.getResourcePath());
        return Result.fail("文件不存在："+e.getResourcePath());
    }

    @ExceptionHandler({HandlerMethodValidationException.class, MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result agrHandler(Exception e){
        log.error("参数不合法，e：{}",e.getMessage());
        return Result.fail("参数不合法：");
    }
}
